package cn.pconline.autoclub.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Subject;
import cn.pconline.autoclub.entity.SubjectPhoto;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.SubjectService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
public class SubjectInfoController {
    @Autowired
	private UserService userService;

    @Autowired
    private SubjectService subjectService;
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private SystemConfig systemConfig;
    
    private static final Logger log = LoggerFactory.getLogger(SubjectInfoController.class);
   
    private final static int MAX_PAGESIZE = 100;
    private final static int MIN_PAGESIZE = 1;
    /**热门话题列表**/
    private final static int HOT_SUBJECT_LIST = 1;
    /**最新话题列表**/
    private final static int NEW_SUBJECT_LIST = 2;
    

    
    @RequestMapping(value = "/subject/listSubject.do", method = RequestMethod.GET)
    public String listSubject(HttpServletRequest request, HttpServletResponse response){
    	 WebUtils.setEncoding(request, response);
         int pageNo = WebUtils.paramInt(request, "pageNo", 1);
         int type = WebUtils.paramInt(request, "type", HOT_SUBJECT_LIST);
         int pageSize = WebUtils.paramInt(request, "pageSize", 10, MIN_PAGESIZE, MAX_PAGESIZE);
         if (pageNo < 1) {
             try {
                 response.sendError(404);
             } catch (Exception e) {
                 log.error("listSubject response.sendError(404) 失败", e);
             }
             return "/template/common/notFoundPage";
         }
         Pager<Subject>  pager = null;
         if(type == HOT_SUBJECT_LIST){
             Date beginDate = DateUtils.getSingleDateBefore(new Date(), 7);
             pager = subjectService.pageSubjectByHot(pageNo,pageSize,beginDate);
        	 //pager = subjectService.pageSubjectByHot(pageNo, pageSize);
         }
         if(type == NEW_SUBJECT_LIST){
        	 pager = subjectService.pageSubjectByNew(pageNo, pageSize);
         }
         if(pager != null && pager.getResultList().size() > 0 ){
        	   WebUtils.checkPageMaxNo(response, pageNo, pager.getPageCount());//超过最大页数，404
        	   List<Subject> subjects = new ArrayList<Subject>(pager.getResultList().size()) ;
        	   for(int i=0; i< pager.getResultList().size(); i++){
                   Subject subject =  pager.getResultList().get(i);
                   subject.setCreateName(userService.getNickNameByUserId(subject.getCreateBy()));
                   subjects.add(subject);
               }
        	   request.setAttribute("subjects", subjects);
        	   
         }
         request.setAttribute("pager", pager);	
         request.setAttribute("type", type);
		 return "template/subject/subjectList";
    }
    
    /**
     * 更新导语
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/subject/updateIntroduction.do", method = RequestMethod.POST)
    public void updateIntroduction(HttpServletRequest request, HttpServletResponse response){
    	WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        String introduction = WebUtils.param( request, "introduction", "" );
        JSONArray imagesArray = WebUtils.parseArray(request, "images");
        String cover = WebUtils.param(request, "cover", "");
        long subjectId = WebUtils.paramLong( request, "subjectId", 0);
        Subject subject = subjectService.findSubjectById(subjectId);
        if(subject==null){
        	AppUtils.printErrorMsg(response,"操作失败，话题不存在", callback);
        	return;
        }
        User user = userAuth.getUser(request, response);//验证用户是否登录
        long supperMan = systemConfig.getSubjectSupperMan();
        if(user.getUid()!=subject.getCreateBy() && user.getUid() != supperMan) {
        	AppUtils.printErrorMsg(response,"操作失败，没有权限", callback);
        	return;
        }
        if (StringUtils.length(introduction) > Subject.DEFAULT_MAX_INTRODUCTION_LENGTH) {
        	AppUtils.printErrorMsg(response,"操作失败，导语字数超出"+Subject.DEFAULT_MAX_INTRODUCTION_LENGTH, callback);
        	return;
        }
        if(imagesArray != null && imagesArray.size()>Subject.MAX_PHOTO_SIZE){
            AppUtils.printErrorMsg(response,"操作失败，导语图片数量超过"+Subject.MAX_PHOTO_SIZE+"张",callback);
            return;
        }
        //当话题有图片时先删除图片
        if(subject.hasPic()){
            subjectService.deleteSubjectPhoto(subjectId);
            subject.setIsPic(Subject.NOT_PIC);
        }
        if(!StringUtils.isBlank(cover)){
            subject.setLogo(cover);
        }
        //创建导语图片
        if(imagesArray != null && !imagesArray.isEmpty()){
            List<SubjectPhoto> photos = new ArrayList<SubjectPhoto>();
            for(int i = 0 ;i < imagesArray.size();i++){
                JSONObject o = imagesArray.getJSONObject(i);
                SubjectPhoto subjectPhoto = new SubjectPhoto();
                subjectPhoto.setSubjectId(subjectId);
                subjectPhoto.setUrl(o.getString("url"));
                subjectPhoto.setSeq(o.getIntValue("seq"));
                photos.add(subjectPhoto);
                if(o.getIntValue("isCover") == SubjectPhoto.IS_COVER){
                    subject.setLogo(o.getString("url"));
                }
            }
            if(subjectService.batchCreatePhoto(photos)){
                subject.setIsPic(Subject.HAS_PIC);
            };
        }
        subject.setIntroduction( introduction );
        int result =subjectService.updateByField( subject, "introduction,is_pic,logo" );
        if(result>0){
        	AppUtils.printSuccessMsg( response, "更新成功", null, callback );
        	return;
        }
        AppUtils.printErrorMsg(response,"更新失败", callback);
        
    }
    
    /**
     * PV +1
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/subject/addPV.do", method = RequestMethod.POST)
    public void addPV(HttpServletRequest request, HttpServletResponse response){
    	WebUtils.setEncoding(request, response);
    	long subjectId = WebUtils.paramLong( request, "subjectId", 0);
        Subject subject = subjectService.findSubjectById(subjectId);
        if(subject==null){
        	AppUtils.printErrorMsg(response,"操作失败，话题不存在", "");
        	return;
        }
        long count = subject.getPvCount()+1;
        subject.setPvCount(count);
        int result =subjectService.updateByField( subject, "pv_count");
        if(result>0){
        	AppUtils.printSuccessMsg( response, "更新成功", null, "" );
        	return;
        }
        AppUtils.printErrorMsg(response,"更新失败", "");
    }
    
    /**
     * 上传图片
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/subject/uploadPic.do", method = RequestMethod.POST)
    public void uploadPic(HttpServletRequest request, HttpServletResponse response){
    	WebUtils.setEncoding(request, response);
    	String field = WebUtils.param( request, "field", "");
    	String url = WebUtils.param( request, "url", "");
    	long subjectId = WebUtils.paramLong( request, "subjectId", 0);
    	Subject subject = subjectService.findSubjectById(subjectId);
    	if(subject==null){
        	AppUtils.printErrorMsg(response,"操作失败，话题不存在", "");
        	return;
        }
    	User user = userAuth.getUser(request, response);//验证用户是否登录
    	long supperMan = systemConfig.getSubjectSupperMan();
        if(user.getUid()!=subject.getCreateBy() && user.getUid() != supperMan){
        	AppUtils.printErrorMsg(response,"操作失败，没有权限", "");
        	return;
        }
    	if(StringUtils.isBlank(url)){
    		AppUtils.printErrorMsg(response,"操作失败，图片不符合规则", "");
        	return;
    	}
    	if(StringUtils.isBlank(field)){
    		AppUtils.printErrorMsg(response,"上传失败", "");
        	return;
    	}
    	if("logo".equals(field)){
    		subject.setLogo( url );
    	}else if("cover".equals(field)){
    		subject.setCover( url );
    	}
    	int result =subjectService.updateByField( subject, field );
    	if(result>0){
    		AppUtils.printSuccessMsg( response, "更新成功", null, "" );
    		return;
    	}
    	AppUtils.printErrorMsg(response,"更新失败", "");
    }
}
